package com.cloud.rou.im.connection.container.manager;

import com.cloud.rou.im.connection.container.listen.DestroyedSessionListener;
import com.cloud.rou.im.connection.container.listen.LogSessionListener;
import com.cloud.rou.im.connection.container.listen.SessionListener;
import com.cloud.rou.im.connection.container.repository.UserConnectorRepository;
import com.cloud.rou.im.connection.container.session.ConnectSessionFactory;
import com.cloud.rou.im.connection.container.session.Session;
import com.cloud.rou.im.core.util.SingletonUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class SessionManager {

    private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);

    private UserConnectorRepository repository;

    private List<SessionListener> listeners=new ArrayList<>();

    private SessionManager(UserConnectorRepository repository) {
        this.repository = repository;
    }

    public static SessionManager newInstance(UserConnectorRepository repository) {
        return SingletonUtil.get(SessionManager.class, repository);
    }


    public Session getConnectSessionByUserId(Long userId) {
        logger.debug("[get conn on this machine] userId: {}", userId);
        Session session = repository.getConnectSession(userId);
        if (session == null) {
            logger.debug("[get conn this machine] netId not found");
            return null;
        }
        return session;
    }

    public synchronized Session createSession(Long userId, ChannelHandlerContext ctx) {
        Session session = ConnectSessionFactory.createSession(userId, ctx);
        repository.addConnectSession(session);
        session.addListener(new LogSessionListener());
        session.addListener(new DestroyedSessionListener());
        session.created();
        return session;
    }

    public void removeConnectSession(Session session) {
        repository.removeConnectSession(session.getUserId());
    }

    public void removeConnectSession(Long userId) {
        repository.removeConnectSession(userId);
    }

    public void addListener(SessionListener listener){
        listeners.add(listener);
    }
    public void addListeners(SessionListener ... listeners){
        Collections.addAll(this.listeners,listeners);
    }
    public void removeAllListener(){
        listeners.clear();
    }

}
